//
//  AtWillRunVC.m
//  DefendHealth
//
//  Created by UNOHACHA on 17/3/4.
//  Copyright © 2017年 iMacOne. All rights reserved.
//

#import "AtWillRunVC.h"

#import <MAMapKit/MAMapKit.h>
//
#import "SGSportTrackingLine.h"

#import <AMapFoundationKit/AMapFoundationKit.h>

#import "MovingAnnotationView.h"

#import "TracingPoint.h"

#import "AtWllRunView.h"

#import "LBXAlertAction.h"

#import "SGSportTracking.h"

#import "GCDDownView.h"



@interface AtWillRunVC () <MAMapViewDelegate>
{
    
    //    / 起始位置
    CLLocation *_UserStartLocation;
    //    / 所有运动线条模型的数组
    //        NSMutableArray <SGSportTrackingLine *>*_trackingLines;
    
    
    
    AtWllRunView * _atView;
//    GCDDownView * _gcdVC;
    
    BOOL  _isRuning;
}
@property (nonatomic,strong) MAMapView * mapView;

//运动轨迹追踪模型
@property(nonatomic,strong) SGSportTracking *sportTracking;


@end

@implementation AtWillRunVC

- (void)leftEvents {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (MAMapView *)mapView {
    
    if (!_mapView ) {
        _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight/3*2)];
        _mapView.showsCompass = NO;
        _mapView.showsScale = NO;
        _mapView.zoomLevel = 10;
        [_mapView setShowsUserLocation:YES];
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
        //        _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
        //        _mapView.allowsBackgroundLocationUpdates = YES;
        _mapView.delegate = self;
        _mapView.pausesLocationUpdatesAutomatically = NO;
        _mapView.logoCenter = CGPointMake(35, _mapView.height-50);
        
    }
    
    return _mapView;
}



- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
  
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.Nav.backgroundColor = kClearColor;
    [self.leftbutton setImage:nil forState:UIControlStateNormal];
    [self.leftbutton endEditing:NO];
    [self.rigltbutton setImage:IMAGE(@"operation-map") forState:UIControlStateNormal];
    
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    
//    dispatch_async(queue, ^{
//        
//    });
    
    [self.view addSubview:self.mapView];
    [self viewShard];

    
    [self.view bringSubviewToFront:self.Nav];
    
    
   
    
}

-(void)viewShard {// kMaxY(_mapView.frame)+70 //kMaxY(_mapView.frame)-70
    
    AtWllRunView * View = [[AtWllRunView alloc]initWithFrame:CGRectMake(0, kScreenHeight/3*2-70, kScreenWidth, kScreenHeight- kScreenHeight/3*2+70)];
//    __block typeof(AtWllRunView *) weakView = View;
    View.newBlock = ^(NSString *type,BOOL RunOn){
        if (![type isEqualToString:@"stop"]) {
            _isRuning = RunOn;
        }else {
            [self runStop];
        }
    };
    
    [self.view addSubview:View];
    _atView = View;
    
    
    GCDDownView * DownVC = [[GCDDownView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:DownVC];

    [DownVC animationViewBlock:^{
        _isRuning = YES;
        [View timerBegin];
    }];
    
}



#pragma mark -- 设置起点图片
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]){
        static NSString *annIdentifier = @"villain";
        MAAnnotationView *mapMaav = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:annIdentifier];
        if (mapMaav == nil) {
            mapMaav = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annIdentifier];
            mapMaav.image = [UIImage imageNamed:@"villain"];
        }
        return mapMaav;
    }
    
    //    else {
    //        static NSString *annIdentifier = @"cirlce";
    //        MAAnnotationView *mapMaav = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:annIdentifier];
    //        if (mapMaav == nil) {
    //            mapMaav = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annIdentifier];
    //            mapMaav.image = [UIImage imageNamed:@"cirlce"];
    //        }
    //        return mapMaav;
    //    }
    return nil;
}




#pragma mark - MAMapView代理方法
/**
 * @brief 位置或者设备方向更新后，会调用此函数
 * @param mapView 地图View
 * @param userLocation 用户定位信息(包括位置与设备方向等数据)
 * @param updatingLocation 标示是否是location数据更新, YES:location数据更新 NO:heading数据更新
 */
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
        if (!updatingLocation) {
            return;
        }
    
    // 1. 判断运动状态，只有`继续`才需要绘制运动轨迹
    if (!_isRuning) {
        return;
        
    }
    
    NSLog(@"%@",userLocation.location);
    
    
    // 判断起始位置是否存在
    if (_UserStartLocation == nil) {
        _UserStartLocation = userLocation.location;
        // 1. 实例化大头针
        MAPointAnnotation *annotaion = [MAPointAnnotation new];
        // 2. 指定坐标位置
        annotaion.coordinate = userLocation.location.coordinate;
        // 3. 添加到地图视图
        [mapView addAnnotation:annotaion];
        
        //        _duration = 1.0;
        [mapView setZoomLevel:15 animated:YES];
        [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
        
    }
    
    
    //    _atView.kcalL.text = NSString(@"%.2f", _sportTracking.totalDistance);
    //
    //    _maSpL.text = NSString(@"%02li",((hour*min+min)/[NSString(@"%f",_sportTracking.totalDistance) integerValue]));
    
    
    
    // 绘制轨迹模型
    [mapView addOverlay:[_sportTracking appendLocation:userLocation.location]];
    
}

#pragma mark - 划线代理
// 需要实现MAMapViewDelegate的-mapView:rendererForOverlay:
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    
    // 1. 判断 overlay 的类型
    if (![overlay isKindOfClass:[MAPolyline class]]) {
        return nil;
    }
    
    // 2. 实例化折线渲染器
    SGPolyLine *polyline = (SGPolyLine *)overlay;
    
    MAPolylineRenderer *renderer = [[MAPolylineRenderer alloc] initWithPolyline:polyline];
    
    // 3. 设置显示属性
    renderer.lineWidth = 5;
    renderer.strokeColor = [UIColor blueColor]; //[UIColor redColor];
    
    return renderer;
}


- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [_mapView removeFromSuperview];
    self.mapView = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 结束之后的操作

- (void)runStop{
    
    UIAlertController* alertController = [UIAlertController alertControllerWithTitle:@"结束本次运动"message:@"是否保存本次运动记录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *calec = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        [_atView.timer invalidate];
        _atView.timer = nil;
        [self leftEvents];
        
    }];
    
    [alertController addAction:calec];
    
    [alertController addAction:action];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
